package com.imooc.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.google.gson.Gson;
import com.imooc.base.BaseInfoProperties;
import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.grace.utils.IPUtil;
import com.imooc.grace.utils.Sample;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.RegistLoginBO;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.service.UsersService;
import com.imooc.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.UUID;

@RestController
@RequestMapping("/passport")
@Slf4j
public class PassportController extends BaseInfoProperties {


    @Autowired
    private UsersService usersService;

    @Autowired
    private JWTUtils jwtUtils;

    @PostMapping("/getSMSCode")
    public GraceJSONResult getSMSCode(@RequestParam String mobile,
                                      HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(mobile)) {
            return GraceJSONResult.error();
        }
        //60s 限制 获得用户ip
       String userIp = IPUtil.getRequestIp(request);
       redis.setnx60s(MOBILE_SMSCODE + ":" + userIp,mobile);


        String code = (int)((Math.random() * 9 + 1) * 100000) + "";
        Sample.sendSms(mobile,code);
        log.info("验证码为: {}", code);
        // 验证码存入 redis 用于后续注册登录进行校验
        redis.set(MOBILE_SMSCODE + ":" + mobile,code,30 * 60);
        System.out.println(redis.get(MOBILE_SMSCODE + ":" + mobile));
        return GraceJSONResult.ok();
    }

    @PostMapping("/login")
    public GraceJSONResult login(@Valid @RequestBody RegistLoginBO registLoginBO,
                                 HttpServletRequest request) throws Exception {

        String mobile = registLoginBO.getMobile();
        String code = registLoginBO.getSmsCode();
        // 1. 从redis中获得验证码进行校验是否匹配
        String redisCode = redis.get(MOBILE_SMSCODE + ":" + mobile);
        if (StringUtils.isBlank(redisCode) || !redisCode.equalsIgnoreCase(code)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }

        // 2. 查询数据库，判断用户是否存在
        Users user = usersService.queryMobileIsExist(mobile);
        if (user == null) {
            // 2.1 如果用户为空，表示没有注册过，则为null，需要注册信息入库
            user = usersService.createUser(mobile);
        }
        // 3 保存用户Token
        /*String userToken = TOKEN_USER_PREFIX + SYMBOL_DOT + UUID.randomUUID().toString();
        redis.set(REDIS_USER_TOKEN + ":" + user.getId(),userToken);*/

        String jwt = jwtUtils.createJWTWithPrefix(new Gson().toJson(user),
                                                    //Long.valueOf(1000),
                                                    TOKEN_USER_PREFIX);

        // 4. 用户登录注册成功以后，删除redis中的短信验证码
        redis.del(MOBILE_SMSCODE + ":" + mobile);
        // 5. 返回用户信息
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user,usersVO);
        usersVO.setUserToken(jwt);
        return GraceJSONResult.ok(usersVO);

    }



    @PostMapping("/loginout")
    public GraceJSONResult loginOut(@RequestParam("userId") String userId,
                                 HttpServletRequest request) throws Exception {
        //后端只需要清除相关的用户信息，用户token
        redis.del(REDIS_USER_TOKEN + ":" + userId);
        return GraceJSONResult.ok();
    }



}
